package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeListVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendsApi friendsApi;
    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private RecommendUserApi recommendUserApi;
    //保存用户资料
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将头像上传到阿里云OSS
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度AI检测是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含：抛出异常
        if(!detect) {
            //throw new RuntimeException("没有人脸");
            //抛出自定义的异常
//            ErrorResult result = new ErrorResult();
//            result.setErrCode("00002");
//            result.setErrMessage("上传的头像中没有包含人脸");
            throw new BusinessException(ErrorResult.faceError());
        }
        //2.2 如果存在，调用API更新
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(imageUrl);
        userInfoApi.update(userInfo);
    }

    //根据id查询
    public UserInfoVo findById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);  //将对象1的同名，同类型属性，自动copy到对象2中
        vo.setAge(userInfo.getAge() == null ?"18":userInfo.getAge().toString());
        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }


    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * 参数：
     *    地址参数：type
     *          1 互相关注
     *          2 我关注
     *          3 粉丝
     *          4 谁看过我
     *    page，pagesize
     * 返回值：
     *    PageResult<UserLikeListVo>
     */
    public PageResult friends(Integer type, Integer page, Integer pagesize) {
        if (type == 4) {
            //实战中的查询

            //1、调用API根据用户id查询：List<Visitors>
            List<Visitors> list = visitorsApi.findByUserId(UserHolder.getUserId(), page, pagesize);
            //2、将List<Visitors>转化为 List<UserLikeListVo>
            //3、获取用户id的集合
            List<Long> userIds = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
            //4、查询用户数据
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
            List<UserLikeListVo> vos = new ArrayList<>();
            for (Visitors visitors : list) {
                UserInfo info = map.get(visitors.getVisitorUserId());
                if (info != null) {
                    UserLikeListVo vo = UserLikeListVo.init(info, visitors);
                    vos.add(vo);
                }
            }
            String key = Constants.VISITORS_USER;
            String hashKey = UserHolder.getUserId().toString();
            String value = System.currentTimeMillis() + "";
            redisTemplate.opsForHash().put(key, hashKey, value);
            //5、构造返回值
            return new PageResult(page, pagesize, 0l, vos);
        }else if (type == 1 ){
            //1.调用Api查看当前用户的好友列表
            List<Friend> friends = friendsApi.findByUserId(UserHolder.getUserId(), page, pagesize);
            //2.获取当前用户好友对应的ids
            List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
            //3.根据好友id查询出来对应的userInfo
            Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds, null);
            //4.构造返回值
            List<UserLikeListVo> vo =new ArrayList<>();
            for (Friend friend : friends) {
                //获取好友的个人信息
                UserInfo userInfo = map.get(friend.getFriendId());
                if (userInfo != null){
                    //查看匹配度
                    RecommendUser recommendUser = recommendUserApi.queryByUserId(friend.getFriendId(), UserHolder.getUserId());
                    //查询喜欢列表的userholder是否是用户id
                    UserLike userLike = userLikeApi.find(UserHolder.getUserId(),friend.getFriendId());
                    if (userLike == null){
                        userLike = new UserLike();
                        userLike.setIsLike(true);
                    }
                    UserLikeListVo init = UserLikeListVo.init(userInfo, userLike, recommendUser);
                    vo.add(init);
                }
            }
            return new PageResult(page,pagesize,0l,vo);
        }else if (type == 2 ){
            //1.查询我关注的userLike集合
            List<UserLike> list = userLikeApi.findByPage(UserHolder.getUserId(), page, pagesize);
            //获取我喜欢的用户id
            List<Long> likeUserIds = CollUtil.getFieldValues(list, "likeUserId", Long.class);
            //将查询到的userInfo封装到map集合中
            Map<Long, UserInfo> map = userInfoApi.findByIds(likeUserIds, null);
            List<UserLikeListVo> vo = new ArrayList<>();
            for (UserLike userLike : list) {
                UserInfo userInfo = map.get(userLike.getLikeUserId());
                RecommendUser recommendUser = null;
                if (userInfo !=null){
                    //获取我喜欢的用户对我的匹配度
                     recommendUser = recommendUserApi.queryByUserId(userLike.getLikeUserId(), UserHolder.getUserId());
                    vo.add(UserLikeListVo.init(userInfo,userLike,recommendUser));
                }
            }
            return new PageResult(page,pagesize,0l,vo);
        }else if (type == 3){
            //1.查询喜欢我的粉丝
            List<UserLike> list = userLikeApi.findFansByPage(UserHolder.getUserId(), page, pagesize);
            ///2.获取粉丝id
            List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
            //3.获取粉丝对应的用户信息
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
            List<UserLikeListVo> vo = new ArrayList<>();
            //遍历粉丝的集合
            for (UserLike userLike : list) {
                UserInfo userInfo = map.get(userLike.getUserId());
                if (userInfo !=null){
                    //查看粉丝对我的匹配度
                    RecommendUser recommendUser = recommendUserApi.queryByUserId(userLike.getUserId(), UserHolder.getUserId());
                    //我是否喜欢该粉丝
                    userLike = userLikeApi.find(UserHolder.getUserId(), userLike.getUserId());
                    if (userLike ==null){
                        userLike = new UserLike();
                        userLike.setIsLike(false);
                    }
                    UserLikeListVo init = UserLikeListVo.init(userInfo, userLike, recommendUser);
                    vo.add(init);
                }
            }
            return new PageResult(page,pagesize,0l,vo);
        }else {
            return new PageResult();
        }
    }

    //互相喜欢，喜欢，粉丝 - 统计
    public Map counts() {
        //1.根据当前id,查询好友数量（查询friend列表）
        Long eachLoveCount = friendsApi.findById(UserHolder.getUserId());
        //2.根据当前id查询我关注的数量userId，查询likeuserid的数量
        Long loveCount = userLikeApi.findLoveCount(UserHolder.getUserId());
        //3.根据当前id查询我的数量，根据likeuserId查询userId的数量
        Long fanCount = userLikeApi.findFanCount(UserHolder.getUserId());
        //4.构建返回值
        Map<String,Long>map = new HashMap<>();
        map.put("eachLoveCount",eachLoveCount);
        map.put("loveCount",loveCount);
        map.put("fanCount",fanCount);
        return map;
    }
    //取消喜欢用户中的某个用户
    public void rescindLike(Long uid) {

        userLikeApi.rescindLike(UserHolder.getUserId(),uid);
        //查询表中该用户是否是粉丝，如果是删除好友
        Boolean b = friendsApi.find(UserHolder.getUserId(),uid);
        if (b) {
            //取消喜欢
            friendsApi.remove(UserHolder.getUserId(),uid);
            //删除环信链接
            huanXinTemplate.deleteContact("hx"+UserHolder.getUserId(),"hx"+uid);
        }
    }
    //添加粉丝为好友
    public void fans(Long uid) {
        //保存我对该粉丝的喜欢状态
        Long userId = UserHolder.getUserId();
        UserLike userLike = new UserLike();
        userLike.setUserId(userId);
        userLike.setLikeUserId(uid);
        userLike.setIsLike(true);
        userLikeApi.fans(userLike);
        //2.添加好友，保存到好友列表
        friendsApi.save(userId,uid);
        huanXinTemplate.addContact("hx"+userId,"hx"+uid);
    }
}
